<template>
  <div class="learning-path-detail-container">
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>加载学习路径中...</p>
    </div>
    
    <div v-else-if="error" class="error-message">
      <p>{{ error }}</p>
      <button @click="fetchLearningPath" class="btn-retry">重试</button>
    </div>
    
    <div v-else class="learning-path-content">
      <div class="path-header">
        <div class="back-button" @click="goBack">
          <span class="back-icon">←</span> 返回
        </div>
        
        <div class="path-title-section">
          <h1>{{ learningPath.title }}</h1>
          <p class="path-description">{{ learningPath.description }}</p>
          
          <div class="path-meta">
            <span class="document-badge" v-if="learningPath.documentId">
              文档: {{ learningPath.documentId.title }}
            </span>
            <span :class="['status-badge', getStatusClass(userProgress.status)]">
              {{ getStatusText(userProgress.status) }}
            </span>
          </div>
        </div>
        
        <div class="path-actions">
          <button 
            @click="startLearning" 
            class="btn-start"
          >
            {{ userProgress.status === 'not_started' ? '开始学习' : 
               userProgress.status === 'completed' ? '复习' : '继续学习' }}
          </button>
        </div>
      </div>
      
      <div class="progress-overview">
        <div class="progress-container">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: `${userProgress.progress}%` }"></div>
          </div>
          <div class="progress-stats">
            <span class="progress-text">{{ userProgress.progress }}% 完成</span>
            <span class="progress-details">
              {{ getCompletedStepsCount() }} / {{ getTotalStepsCount() }} 步骤
            </span>
          </div>
        </div>
      </div>
      
      <div class="path-content">
        <div class="stages-list">
          <div 
            v-for="(stage, stageIndex) in learningPath.stages" 
            :key="stage._id"
            class="stage-item"
          >
            <div class="stage-header" @click="toggleStage(stageIndex)">
              <div class="stage-info">
                <span :class="['stage-status', getStageStatusClass(stageIndex)]"></span>
                <h3>{{ stage.title }}</h3>
              </div>
              <div class="stage-meta">
                <span class="step-count">{{ getCompletedStepsInStage(stageIndex) }}/{{ stage.steps.length }} 步骤</span>
                <span class="toggle-icon">{{ expandedStages[stageIndex] ? '▼' : '►' }}</span>
              </div>
            </div>
            
            <div v-if="expandedStages[stageIndex]" class="stage-steps">
              <p class="stage-description">{{ stage.description }}</p>
              
              <div 
                v-for="(step, stepIndex) in stage.steps" 
                :key="step._id"
                :class="['step-item', getStepStatusClass(stageIndex, stepIndex)]"
              >
                <div class="step-header">
                  <div class="step-info">
                    <span class="step-icon">{{ step.cardId ? '📝' : '🧩' }}</span>
                    <span class="step-title">{{ step.title }}</span>
                  </div>
                  <div class="step-actions">
                    <span class="step-type">{{ step.cardId ? '学习卡片' : '练习题' }}</span>
                    <button 
                      v-if="canAccessStep(stageIndex, stepIndex)"
                      @click="goToStep(stageIndex, stepIndex)" 
                      class="btn-step"
                    >
                      {{ getStepButtonText(stageIndex, stepIndex) }}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { learningPathApi } from '@/services/api';

const route = useRoute();
const router = useRouter();
const learningPath = ref({});
const userProgress = ref({});
const loading = ref(true);
const error = ref(null);
const expandedStages = ref({});

// 获取学习路径详情
const fetchLearningPath = async () => {
  loading.value = true;
  error.value = null;
  
  try {
    console.log(`[LearningPathDetailView] 开始获取学习路径 ${route.params.id} 详情`);
    const response = await learningPathApi.getPathById(route.params.id);
    console.log('[LearningPathDetailView] 获取学习路径详情响应:', response.data);
    
    if (response.data) {
      learningPath.value = response.data;
      console.log(`[LearningPathDetailView] 成功获取学习路径详情:`, learningPath.value);
    } else {
      console.warn('[LearningPathDetailView] 响应中没有学习路径数据');
      error.value = '未找到学习路径数据';
    }
  } catch (err) {
    console.error('[LearningPathDetailView] 获取学习路径详情失败:', err);
    error.value = '获取学习路径详情失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 切换阶段展开/折叠状态
const toggleStage = (stageIndex) => {
  expandedStages.value[stageIndex] = !expandedStages.value[stageIndex];
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'not_started': '未开始',
    'in_progress': '学习中',
    'completed': '已完成'
  };
  return statusMap[status] || status;
};

// 获取状态类名
const getStatusClass = (status) => {
  return status.replace('_', '-');
};

// 获取阶段状态类名
const getStageStatusClass = (stageIndex) => {
  if (!userProgress.value.stagesProgress) return '';
  
  const stageProgress = userProgress.value.stagesProgress[stageIndex];
  if (!stageProgress) return '';
  
  return `status-${stageProgress.status.replace('_', '-')}`;
};

// 获取步骤状态类名
const getStepStatusClass = (stageIndex, stepIndex) => {
  if (!userProgress.value.stagesProgress) return '';
  
  const stageProgress = userProgress.value.stagesProgress[stageIndex];
  if (!stageProgress || !stageProgress.stepsProgress) return '';
  
  const stepProgress = stageProgress.stepsProgress[stepIndex];
  if (!stepProgress) return '';
  
  return `status-${stepProgress.status.replace('_', '-')}`;
};

// 获取已完成的步骤数量
const getCompletedStepsCount = () => {
  if (!userProgress.value.stagesProgress) return 0;
  
  return userProgress.value.stagesProgress.reduce((total, stage) => {
    if (!stage.stepsProgress) return total;
    return total + stage.stepsProgress.filter(step => step.status === 'completed').length;
  }, 0);
};

// 获取总步骤数量
const getTotalStepsCount = () => {
  if (!learningPath.value.stages) return 0;
  
  return learningPath.value.stages.reduce((total, stage) => {
    return total + stage.steps.length;
  }, 0);
};

// 获取阶段中已完成的步骤数量
const getCompletedStepsInStage = (stageIndex) => {
  if (!userProgress.value.stagesProgress) return 0;
  
  const stageProgress = userProgress.value.stagesProgress[stageIndex];
  if (!stageProgress || !stageProgress.stepsProgress) return 0;
  
  return stageProgress.stepsProgress.filter(step => step.status === 'completed').length;
};

// 是否可以访问步骤
const canAccessStep = (stageIndex, stepIndex) => {
  // 如果是当前阶段之前的阶段，或者是当前阶段的已完成步骤或当前步骤，则可以访问
  const currentStageIndex = userProgress.value.currentStageIndex || 0;
  const currentStepIndex = userProgress.value.currentStepIndex || 0;
  
  if (stageIndex < currentStageIndex) return true;
  if (stageIndex === currentStageIndex && stepIndex <= currentStepIndex) return true;
  
  // 检查该步骤的状态
  if (userProgress.value.stagesProgress && 
      userProgress.value.stagesProgress[stageIndex] && 
      userProgress.value.stagesProgress[stageIndex].stepsProgress) {
    const stepStatus = userProgress.value.stagesProgress[stageIndex].stepsProgress[stepIndex].status;
    return stepStatus === 'completed';
  }
  
  return false;
};

// 获取步骤按钮文本
const getStepButtonText = (stageIndex, stepIndex) => {
  if (!userProgress.value.stagesProgress) return '开始';
  
  const stageProgress = userProgress.value.stagesProgress[stageIndex];
  if (!stageProgress || !stageProgress.stepsProgress) return '开始';
  
  const stepProgress = stageProgress.stepsProgress[stepIndex];
  if (!stepProgress) return '开始';
  
  switch (stepProgress.status) {
    case 'completed': return '复习';
    case 'in_progress': return '继续';
    default: return '开始';
  }
};

// 开始学习
const startLearning = () => {
  router.push(`/learning/${route.params.id}`);
};

// 前往特定步骤
const goToStep = (stageIndex, stepIndex) => {
  router.push(`/learning/${route.params.id}?stage=${stageIndex}&step=${stepIndex}`);
};

// 返回上一页
const goBack = () => {
  router.push('/learning-paths');
};

onMounted(() => {
  fetchLearningPath();
});
</script>

<style scoped>
.learning-path-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.loading, .error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top: 4px solid #4CAF50;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  color: #d32f2f;
}

.btn-retry {
  background-color: #f1f1f1;
  border: none;
  border-radius: 4px;
  padding: 0.6rem 1rem;
  margin-top: 1rem;
  cursor: pointer;
}

.path-header {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 2rem;
}

.back-button {
  display: inline-flex;
  align-items: center;
  color: #666;
  cursor: pointer;
  font-size: 0.9rem;
  margin-bottom: 1rem;
}

.back-icon {
  margin-right: 0.5rem;
  font-size: 1.2rem;
}

.path-title-section h1 {
  margin-bottom: 0.5rem;
  color: #333;
}

.path-description {
  color: #666;
  margin-bottom: 1rem;
}

.path-meta {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.document-badge, .status-badge {
  padding: 0.3rem 0.6rem;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}

.document-badge {
  background-color: #f1f1f1;
  color: #666;
}

.not-started {
  background-color: #e3f2fd;
  color: #1976d2;
}

.in-progress {
  background-color: #fff8e1;
  color: #ff8f00;
}

.completed {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.path-actions {
  margin-bottom: 1rem;
}

.btn-start {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.8rem 1.5rem;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.btn-start:hover {
  background-color: #45a049;
}

.progress-overview {
  margin-bottom: 2rem;
}

.progress-container {
  margin-bottom: 1rem;
}

.progress-bar {
  height: 10px;
  background-color: #f1f1f1;
  border-radius: 5px;
  margin-bottom: 0.5rem;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #4CAF50;
  border-radius: 5px;
  transition: width 0.3s ease;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
}

.progress-text {
  font-weight: bold;
  color: #333;
}

.progress-details {
  color: #666;
}

.stages-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.stage-item {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.stage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.stage-header:hover {
  background-color: #f9f9f9;
}

.stage-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.stage-status {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #ccc;
}

.status-completed {
  background-color: #4CAF50;
}

.status-in-progress {
  background-color: #FF9800;
}

.status-not-started {
  background-color: #ccc;
}

.stage-meta {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.step-count {
  color: #666;
  font-size: 0.9rem;
}

.toggle-icon {
  color: #666;
  font-size: 0.8rem;
}

.stage-steps {
  padding: 1rem 1.5rem;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
}

.stage-description {
  margin-bottom: 1rem;
  color: #666;
}

.step-item {
  padding: 1rem;
  margin-bottom: 0.5rem;
  border-radius: 4px;
  background-color: white;
  border-left: 3px solid #ccc;
}

.step-item.status-completed {
  border-left-color: #4CAF50;
}

.step-item.status-in-progress {
  border-left-color: #FF9800;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.step-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.step-icon {
  font-size: 1.2rem;
}

.step-actions {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.step-type {
  color: #666;
  font-size: 0.8rem;
}

.btn-step {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.4rem 0.8rem;
  font-size: 0.9rem;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.btn-step:hover {
  background-color: #45a049;
}

@media (max-width: 768px) {
  .path-header {
    flex-direction: column;
  }
  
  .path-meta, .stage-header, .step-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .stage-meta, .step-actions {
    margin-top: 0.5rem;
    width: 100%;
    justify-content: space-between;
  }
}
</style> 